package com.heima.admin.interceptor;

import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.common.AdminThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从request获取adminId并存到ThreadLocal对象中
        String adminId = request.getHeader("adminId");
        if(StringUtils.isNotEmpty(adminId)){
            AdUser adUser = new AdUser();
            adUser.setId(Integer.parseInt(adminId));

            AdminThreadLocalUtil.setUser(adUser);
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //防止内存泄漏
        AdminThreadLocalUtil.clear();
    }
}
